#!/usr/bin/env python
# encoding: utf-8
"""
Validate.py

Created by Pablo Ortega Mesa on 2011-01-28.
Copyright (c) 2011 Toeska Research Group. All rights reserved.
"""
from xml.dom import minidom
import sys

def validateExtent(valueFilename,xmlFilename):
	print "Validate Extent...."
	docs = []
	fValues = open(valueFilename,"r")
	for line in fValues:
		line = line.split("\n")[0]
		docs.append(line.split("\t")[0])
	fValues.close()

	objs = []
	try:
		dom = minidom.parse(xmlFilename)
		elements = dom.getElementsByTagName('obj')
		if len(elements) != 0:
			for i in range(0,len(elements)):
				objs.append(elements[i].childNodes[0].nodeValue)
	except:
		print "error en xml"
		sys.exit(0)
	contO = 0
	contF = 0
	for obj in objs:
		line =  "Validating: "+obj
		if obj in docs:
			line += "\t\t\t\t\tOK"
			contO += 1
		else:
			line += "\t\t\t\t\tFAIL"
			contF += 1
		print line
	return contO,contF

def validateIntent(xmlFile,termsFilename):
	print "Validate Intent..."
	terms = []
	try:
		dom = minidom.parse(xmlFile)
		elements = dom.getElementsByTagName('attr')
		if len(elements) != 0:
			for i in range(0,len(elements)):
				terms.append(elements[i].childNodes[0].nodeValue)
	except:
		print "error en xml"
		sys.exit(0)

	termsFile = []
	fValues = open(termsFilename,"r")
	for line in fValues:
		line = line.split("\n")[0]
		termsFile.append(line.split("\t")[0])
	fValues.close()
	contF = 0
	contO = 0
	for term in terms:
		line = "Validating: "+term
		if term in termsFile:
			line += "\t\t\t\t\tOK"
			contO += 1
		else:
			line += "\t\t\t\t\tFAIL"
			contF += 1
		print line
	return contO,contF
	

if len(sys.argv)<4:
	print "ERROR: Usage python "+sys.argv[0]+" [termsFilename] [docsIdFilename] [xmlFilename]"
	sys.exit(0)

termsFilename = sys.argv[1]
docsFilename = sys.argv[2]
xmlFilename = sys.argv[3]

if termsFilename and docsFilename and xmlFilename:
	extentOK,extentFail = validateExtent(docsFilename,xmlFilename)
	intentOk,intentFail = validateIntent(xmlFilename,termsFilename)
	print str(extentOK)+" ok founds in extent"
	print str(extentFail)+" fails founds in extent"
	print str(intentOk)+" ok founds in intent"
	print str(intentFail)+" fails founds in intent"